﻿using System;
using System.Web;
using axCommerce.Data;

namespace axCommerce.Helper.Storage
{
	public class CookieHelper
	{
		private enum Keys
		{
			CustomerId
		}

		private static HttpCookie Get(Keys cookieKey)
		{
			return HttpContext.Current.Request.Cookies[cookieKey.ToString()];
		}

		private static void Set(Keys cookieKey, object cookieValue)
		{
			HttpCookie aCookie = new HttpCookie(cookieKey.ToString());
			if (cookieValue != null)
			{
				aCookie.Values[cookieKey.ToString()] = cookieValue.ToString();
				HttpContext.Current.Response.Cookies.Add(aCookie);
			}
			else
			{
				HttpCookie savedCookie = HttpContext.Current.Request.Cookies[cookieKey.ToString()];
				if (savedCookie != null)
				{
					aCookie = new HttpCookie(savedCookie.Name)
					          	{
					          		Expires = DateTime.Now.AddDays(-1)
					          	};
					HttpContext.Current.Response.Cookies.Add(aCookie);
				}
			}
		}

		public static Customer CookieCustomer
		{
			get
			{
				HttpCookie сookieCustomer = Get(Keys.CustomerId);
				if (сookieCustomer != null)
				{
					string sCustomerId = CryptoHelper.Decrypt(Convert.FromBase64String(сookieCustomer.Value.Substring(Keys.CustomerId.ToString().Length + 1)));
					int iCustomerId;
					if (int.TryParse(sCustomerId, out iCustomerId))
					{
						return Customer.Get(iCustomerId);
					}
				}

				return null;
			}
			set
			{
				Set(Keys.CustomerId,
					value != null && value.CustomerId != null
						? Convert.ToBase64String(CryptoHelper.Encrypt(value.CustomerId.Value.ToString()))
						: null);
			}
		}
	}
}
